layui.define(["element", "layer", "jquery"], function(exports) {
	var element = layui.element,
		layer = layui.layer,
		$ = layui.$;


	var mTab = {
		/**
		 * 初始化tab
		 * @param options
		 */
		render: function(options) {
			options.filter = options.filter || null;
			options.multiModule = options.multiModule || false;
			options.urlHashLocation = options.urlHashLocation || false;
			options.maxTabNum = options.maxTabNum || 20;
			options.menuList = options.menuList || []; // todo 后期菜单想改为不操作dom, 而是直接操作初始化传过来的数据
			options.homeInfo = options.homeInfo || {};
			options.listenSwichCallback = options.listenSwichCallback || function() {};
			mTab.listen(options);
			mTab.listenRoll();
			mTab.listenSwitch(options);
			mTab.listenHash(options);
		},

		/**
		 * 新建tab窗口
		 * @param options.tabId
		 * @param options.href
		 * @param options.title
		 * @param options.isIframe
		 * @param options.maxTabNum
		 */
		create: function(options) {
			options.tabId = options.tabId || null;
			options.href = options.href || null;
			options.title = options.title || null;
			options.isIframe = options.isIframe || false;
			options.maxTabNum = options.maxTabNum || 20;
			if ($(".admin-tab .layui-tab-title li").length >= options.maxTabNum) {
				layer.msg('Tab窗口已达到限定数量，请先关闭部分Tab');
				return false;
			}
			var ele = element;
			if (options.isIframe) ele = parent.layui.element;
			ele.tabAdd('adminTab', {
				title: '<span class="admin-tab-active"></span><span unselectable="on" class="noselect">' + options.title + '</span><i class="layui-icon layui-unselect layui-tab-close">ဆ</i>', //用于演示
				content: '<iframe width="100%" height="100%" frameborder="no" border="0" marginwidth="0" marginheight="0" src="' + options.href + '"></iframe>',
				id: options.tabId
			});

			$('.admin-side').attr('admin-tab-tag', 'add');
			sessionStorage.setItem('adminmenu_' + options.tabId, options.title);
		},


		/**
		 * 切换选项卡
		 * @param tabId
		 */
		change: function(tabId) {
			element.tabChange('adminTab', tabId);
		},

		/**
		 * 删除tab窗口
		 * @param tabId
		 * @param isParent
		 */
		delete: function(tabId, isParent) {
			// todo 未知BUG，不知道是不是layui问题，必须先删除元素
			$(".admin-tab .layui-tab-title .layui-unselect.layui-tab-bar").remove();

			if (isParent === true) {
				parent.layui.element.tabDelete('adminTab', tabId);
			} else {
				element.tabDelete('adminTab', tabId);
			}
		},

		/**
		 * 在iframe层打开新tab方法
		 */
		openNewTabByIframe: function(options) {
			options.href = options.href || null;
			options.title = options.title || null;
			var loading = parent.layer.load(0, { shade: false, time: 2 * 1000 });
			if (options.href === null || options.href === undefined) options.href = new Date().getTime();
			var checkTab = mTab.check(options.href, true);
			if (!checkTab) {
				mTab.create({
					tabId: options.href,
					href: options.href,
					title: options.title,
					isIframe: true
				});
			}

			parent.layui.element.tabChange('adminTab', options.href);
			parent.layer.close(loading);
		},

		/**
		 * 在iframe层关闭当前tab方法
		 */
		deleteCurrentByIframe: function() {
			var ele = $(".admin-tab .layui-tab-title li.layui-this", parent.document);
			if (ele.length > 0) {
				var layId = $(ele[0]).attr('lay-id');
				mTab.delete(layId, true);
			}
		},

		/**
		 * 判断tab窗口
		 */
		check: function(tabId, isIframe) {
			// 判断选项卡上是否有
			var checkTab = false;
			if (isIframe === undefined || isIframe === false) {
				$(".layui-tab-title li").each(function() {
					var checkTabId = $(this).attr('lay-id');
					if (checkTabId != null && checkTabId === tabId) {
						checkTab = true;
					}
				});
			} else {
				parent.layui.$(".layui-tab-title li").each(function() {
					var checkTabId = $(this).attr('lay-id');
					if (checkTabId != null && checkTabId === tabId) {
						checkTab = true;
					}
				});
			}
			return checkTab;
		},

		/**
		 * 开启tab右键菜单
		 * @param tabId
		 * @param left
		 */
		openTabRignMenu: function(tabId, left) {
			mTab.closeTabRignMenu();
			var m = ['<dd><a href="javascript:;" admin-tab-menu-close="current">关 闭 当 前</a></dd>',
					'<dd><a href="javascript:;" admin-tab-menu-close="other">关 闭 其 他</a></dd>',
					'<dd><a href="javascript:;" admin-tab-menu-close="all">关 闭 全 部</a></dd>'
				],
				home = $('.admin-tab .layui-tab-title > li[lay-id="' + tabId + '"]').index() === 0,
				tabLength = $('.admin-tab .layui-tab-title > li').length,
				menuRight = m.join('\n');

			if (home) {
				if (tabLength > 1)
					menuRight = m[1];
				else
					return false;
			} else if (tabLength <= 2)
				menuRight = m[0];

			var menuHtml = '<div class="layui-unselect layui-form-select layui-form-selected admin-tab-mousedown layui-show" data-tab-id="' + tabId + '" style="left: ' + left + 'px;">\n' +
				'<dl>\n' +
				menuRight +
				'\n</dl>\n' +
				'</div>';
			var makeHtml = '<div class="admin-tab-make"></div>';
			$('.admin-tab .layui-tab-title').after(menuHtml);
			$('.admin-tab .layui-tab-content').after(makeHtml);
		},

		/**
		 * 关闭tab右键菜单
		 */
		closeTabRignMenu: function() {
			$('.admin-tab-mousedown').remove();
			$('.admin-tab-make').remove();
		},

		/**
		 * 查询菜单信息
		 * @param href
		 * @param menuList
		 */
		searchMenu: function(href, menuList) {
			var menu;
			for (key in menuList) {
				var item = menuList[key];
				if (item.href === href) {
					menu = item;
					break;
				}
				if (item.child) {
					newMenu = mTab.searchMenu(href, item.child);
					if (newMenu) {
						menu = newMenu;
						break;
					}
				}
			}
			return menu;
		},

		/**
		 * 监听
		 * @param options
		 */
		listen: function(options) {
			options = options || {};
			options.maxTabNum = options.maxTabNum || 20;

			/**
			 * 打开新窗口
			 */
			$('body').on('click', '[admin-href]', function() {
				var loading = layer.load(0, { shade: false, time: 2 * 1000 });
				var tabId = $(this).attr('admin-href'),
					href = $(this).attr('admin-href'),
					title = $(this).text(),
					target = $(this).attr('target');

				var el = $("[admin-href='" + href + "']", ".admin-side");
				layer.close(window.openTips);
				if (el.length) {
					$(el).closest(".layui-nav-tree").find(".layui-this").removeClass("layui-this");
					$(el).parent().addClass("layui-this");
				}

				if (tabId === null || tabId === undefined) tabId = new Date().getTime();
				var tabMenu = $('.admin-header>.admin-header-content>.header-menu-pc>.layui-nav-item.layui-this').attr('data-menu');
				if (tabMenu) {
					tabId = href = tabMenu + '/' + href;
				}

				if (target === '_blank') {
					layer.close(loading);
					window.open(href, "_blank");
					return false;
				}

				var checkTab = mTab.check(tabId);
				if (!checkTab) {
					mTab.create({
						tabId: tabId,
						href: href,
						title: title,
						isIframe: false,
						maxTabNum: options.maxTabNum,
					});
				}
				element.tabChange('adminTab', tabId);
				layer.close(loading);
			});

			/**
			 * 在iframe子菜单上打开新窗口
			 */
			$('body').on('click', '[admin-content-href]', function() {
				var loading = parent.layer.load(0, { shade: false, time: 2 * 1000 });
				var tabId = $(this).attr('admin-content-href'),
					href = $(this).attr('admin-content-href'),
					title = $(this).attr('data-title'),
					target = $(this).attr('target');
				if (target === '_blank') {
					parent.layer.close(loading);
					window.open(href, "_blank");
					return false;
				}
				if (tabId === null || tabId === undefined) tabId = new Date().getTime();
				var checkTab = mTab.check(tabId, true);
				if (!checkTab) {
					mTab.create({
						tabId: tabId,
						href: href,
						title: title,
						isIframe: true,
						maxTabNum: options.maxTabNum,
					});
				}
				parent.layui.element.tabChange('adminTab', tabId);
				parent.layer.close(loading);
			});

			/**
			 * 关闭选项卡
			 **/
			$('body').on('click', '.admin-tab .layui-tab-title .layui-tab-close', function() {
				var loading = layer.load(0, { shade: false, time: 2 * 1000 });
				var $parent = $(this).parent();
				var tabId = $parent.attr('lay-id');
				if (tabId !== undefined || tabId !== null) {
					mTab.delete(tabId);
				}
				layer.close(loading);
			});

			/**
			 * 选项卡操作
			 */
			$('body').on('click', '[admin-tab-close]', function() {
				var loading = layer.load(0, { shade: false, time: 2 * 1000 });
				var closeType = $(this).attr('admin-tab-close');
				$(".admin-tab .layui-tab-title li").each(function() {
					var tabId = $(this).attr('lay-id');
					var id = $(this).attr('id');
					var isCurrent = $(this).hasClass('layui-this');
					if (id !== 'adminHomeTabId') {
						if (closeType === 'all') {
							mTab.delete(tabId);
						} else {
							if (closeType === 'current' && isCurrent) {
								mTab.delete(tabId);
							} else if (closeType === 'other' && !isCurrent) {
								mTab.delete(tabId);
							}
						}
					}
				});
				layer.close(loading);
			});

			/**
			 * 禁用网页右键
			 */
			$(".admin-tab .layui-tab-title").unbind("mousedown").bind("contextmenu", function(e) {
				e.preventDefault();
				return false;
			});

			/**
			 * 注册鼠标右键
			 */
			$('body').on('mousedown', '.admin-tab .layui-tab-title li', function(e) {
				var left = $(this).offset().left - $('.admin-tab').offset().left + ($(this).width() / 2),
					tabId = $(this).attr('lay-id');
				if (e.which === 3) {
					mTab.openTabRignMenu(tabId, left);
				}
			});

			/**
			 * 关闭tab右键菜单
			 */
			$('body').on('click', '.admin-body,.admin-header,.admin-side,.admin-tab-make', function() {
				mTab.closeTabRignMenu();
			});

			/**
			 * tab右键选项卡操作
			 */
			$('body').on('click', '[admin-tab-menu-close]', function() {
				var loading = layer.load(0, { shade: false, time: 2 * 1000 });
				var closeType = $(this).attr('admin-tab-menu-close'),
					currentTabId = $('.admin-tab-mousedown').attr('data-tab-id');
				$(".admin-tab .layui-tab-title li").each(function() {
					var tabId = $(this).attr('lay-id');
					var id = $(this).attr('id');
					if (id !== 'adminHomeTabId') {
						if (closeType === 'all') {
							mTab.delete(tabId);
						} else {
							if (closeType === 'current' && currentTabId === tabId) {
								mTab.delete(tabId);
							} else if (closeType === 'other' && currentTabId !== tabId) {
								mTab.delete(tabId);
							}
						}
					}
				});
				mTab.closeTabRignMenu();
				layer.close(loading);
			});
		},

		/**
		 * 监听tab切换
		 * @param options
		 */
		listenSwitch: function(options) {
			options.filter = options.filter || null;
			options.multiModule = options.multiModule || false;
			options.urlHashLocation = options.urlHashLocation || false;
			options.listenSwichCallback = options.listenSwichCallback || function() {

			};
			element.on('tab(' + options.filter + ')', function(data) {
				var tabId = $(this).attr('lay-id'),
					home = $(this).attr('id') === 'adminHomeTabId';

				if (options.urlHashLocation) {
					location.hash = home ? '' : tabId;
				}

				if (home) {
					history.replaceState(null, null, ' ');
					//return false;
				}

				if (typeof options.listenSwichCallback === 'function') {
					options.listenSwichCallback();
				}
				// 判断是否为新增窗口
				if ($('.admin-side').attr('admin-tab-tag') === 'add') {
					$('.admin-side').attr('admin-tab-tag', 'no')
				} else {
					$("[admin-href]").parent().removeClass('layui-this');
					if (options.multiModule) {
						mTab.listenSwitchMultiModule(tabId);
					} else {
						mTab.listenSwitchSingleModule(tabId);
					}
				}
			});
		},

		/**
		 * 监听hash变化
		 * @param options
		 * @returns {boolean}
		 */
		listenHash: function(options) {
			options.urlHashLocation = options.urlHashLocation || false;
			options.maxTabNum = options.maxTabNum || 20;
			options.homeInfo = options.homeInfo || {};
			options.menuList = options.menuList || [];

			if (!options.urlHashLocation || location.hash === '') return false;

			var re = /^#+((?:[^\/]+\/)*)(([\w\-]+)\.html)?(?:\?(.+)$)?/.exec(location.hash);
			if (!re || !re[2]) return console.log('路由匹配错误', location.hash);

			var module = re[1].replace(/\/+$/, ''),
				tabId = re[1] + re[2],
				href = location.hash.replace(/^#+/, ''),
				param = re[5];

			// 判断是否为首页
			if (tabId === options.homeInfo.href) return false;

			// 判断是否为左侧菜单
			var menuTop = mTab.searchMenu(module, options.menuList);
			if (menuTop && menuTop.hasOwnProperty('child')) {
				var menu = mTab.searchMenu(re[2], menuTop.child);
				if (menu) {
					mTab.create({
						tabId: tabId,
						href: href,
						title: menu.title,
						isIframe: false,
						maxTabNum: options.maxTabNum
					});
					$('.admin-side').attr('admin-tab-tag', 'no');
					element.tabChange('adminTab', tabId);
					return false;
				}
			}

			// 判断是否为快捷菜单
			var isSearchMenu = false;
			$("[admin-content-href]").each(function() {
				if ($(this).attr("admin-content-href") === tabId) {
					var title = $(this).attr("data-title");
					mTab.create({
						tabId: tabId,
						href: tabId,
						title: title,
						isIframe: false,
						maxTabNum: options.maxTabNum,
					});
					$('.admin-side').attr('admin-tab-tag', 'no');
					element.tabChange('adminTab', tabId);
					isSearchMenu = true;
					return false;
				}
			});
			if (isSearchMenu) return false;

			// 既不是左侧菜单、快捷菜单,就直接打开
			var title = sessionStorage.getItem('adminmenu_' + tabId) === null ? tabId : sessionStorage.getItem('adminmenu_' + tabId);
			mTab.create({
				tabId: tabId,
				href: tabId,
				title: title,
				isIframe: false,
				maxTabNum: options.maxTabNum,
			});
			element.tabChange('adminTab', tabId);
			return false;
		},

		/**
		 * 监听滚动
		 */
		listenRoll: function() {
			$(".admin-tab-roll-left").click(function() {
				mTab.rollClick("left");
			});
			$(".admin-tab-roll-right").click(function() {
				mTab.rollClick("right");
			});
		},

		/**
		 * 单模块切换
		 * @param tabId
		 */
		listenSwitchSingleModule: function(tabId) {
			$("[admin-href]").each(function() {
				var module = $(this).parents('.layui-nav.layui-nav-tree.layui-left-nav-tree').attr('id'),
					href = $(this).attr("admin-href");
				if (module) href = module + '/' + href;

				if (href === tabId) {
					// 自动展开菜单栏
					var addMenuClass = function($element, type) {
						if (type === 1) {
							$element.addClass('layui-this');
							if ($element.hasClass('layui-nav-item') && $element.hasClass('layui-this')) {
								$(".admin-header-menu li").attr('class', 'layui-nav-item');
							} else {
								addMenuClass($element.parent().parent(), 2);
							}
						} else {
							$element.addClass('layui-nav-itemed');
							if ($element.hasClass('layui-nav-item') && $element.hasClass('layui-nav-itemed')) {
								$(".admin-header-menu li").attr('class', 'layui-nav-item');
							} else {
								addMenuClass($element.parent().parent(), 2);
							}
						}
					};
					addMenuClass($(this).parent(), 1);
					return false;
				}
			});
		},

		/**
		 * 多模块切换
		 * @param tabId
		 */
		listenSwitchMultiModule: function(tabId) {
			var re = /^#+((?:[^\/]+\/)*)(([\w\-]+)\.html)?(?:\?(.+)$)?/.exec(location.hash);
			if (!re || !re[2]) return false;

			var module = re[1].replace(/\/+$/, ''),
				href = re[2],
				param = re[5];

			$('.layui-nav.header-menu-pc > .layui-nav-item.layui-this, .layui-nav.header-menu-mobile > .layui-nav-item > .layui-nav-child > dd.layui-this', '.admin-header > .admin-header-content').removeClass('layui-this');
			$('.admin-side>.layui-nav.layui-nav-tree.layui-this').removeClass('layui-this').addClass('layui-hide');
			$('.admin-side>.layui-nav.layui-nav-tree .layui-this').removeClass('layui-this');

			var elem = $('.admin-side>.layui-nav.layui-nav-tree[id="' + module + '"]');
			if (elem.length > 0) { // 路由匹配对应模块
				$('.layui-nav.header-menu-pc > .layui-nav-item[id="' + module + 'HeaderId"], .layui-nav.header-menu-mobile > .layui-nav-item > .layui-nav-child > dd:has([id="' + module + 'HeaderId"])', '.admin-header > .admin-header-content').addClass('layui-this');
				elem.removeClass('layui-hide').addClass('layui-this');
				elem = $('.layui-nav-item:has(a[admin-href="' + href + '"])', elem);
				if (elem.length > 0) { // 路由匹配对应左侧菜单
					if (elem.children('.layui-nav-child').length > 0) {
						$('.layui-nav-child:has(a[admin-href="' + href + '"])', elem).slideDown('fast')
							.parent().addClass('layui-nav-itemed');
						$('.layui-nav-child > dd:has(> a[admin-href="' + href + '"])', elem).addClass('layui-this');
					} else {
						elem.addClass('layui-this');
					}
				}
			} else {
				console.log('路由没有匹配到对应的模块和菜单');
				$('.layui-nav.header-menu-pc > .layui-nav-item:first-child, .layui-nav.header-menu-mobile > .layui-nav-item > .layui-nav-child > dd:first-child', '.admin-header > .admin-header-content').addClass('layui-this');
				$('.admin-side>.layui-nav.layui-nav-tree:first-child').removeClass('layui-hide').addClass('layui-this');
			}
		},

		/**
		 * 自动定位
		 */
		rollPosition: function() {
			var $tabTitle = $('.admin-tab .layui-tab-title');
			var autoLeft = 0;
			$tabTitle.children("li").each(function() {
				if ($(this).hasClass('layui-this')) {
					return false;
				} else {
					autoLeft += $(this).outerWidth();
				}
			});
			$tabTitle.animate({
				scrollLeft: autoLeft - $tabTitle.width() / 3
			}, 200);
		},

		/**
		 * 点击滚动
		 * @param direction
		 */
		rollClick: function(direction) {
			var $tabTitle = $('.admin-tab  .layui-tab-title');
			var left = $tabTitle.scrollLeft();
			if ('left' === direction) {
				$tabTitle.animate({
					scrollLeft: left - 450
				}, 200);
			} else {
				$tabTitle.animate({
					scrollLeft: left + 450
				}, 200);
			}
		}
	};

	exports("mTab", mTab);
});